﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using umbraco.cms.presentation.Trees;
using umbraco.cms.businesslogic.datatype;
using TheOutfield.UmbExt.UniversalMediaPicker.Extensions;

namespace TheOutfield.UmbExt.UniversalMediaPicker
{
    public class UniversalMediaPickerAppTree : BaseTree
    {
        public UniversalMediaPickerAppTree(string app)
            : base(app)
        { }

        protected override void CreateRootNode(ref XmlTreeNode rootNode)
        {
            if (!string.IsNullOrEmpty(NodeKey) && NodeKey.Contains("$"))
            {
                var nodeTitle = rootNode.Text;

                var nodeKeyParts = NodeKey.Split('$');
                if (nodeKeyParts.Length >= 1)
                {
                    var dtdId = Convert.ToInt32(nodeKeyParts[0]);
                    if (dtdId != 0)
                    {
                        var provider = UniversalMediaPickerProviderFactory.GetProvider(dtdId);
                        if (provider != null)
                        {
                            nodeTitle = provider.Alias + " " + nodeTitle;
                        }
                    }
                }

                rootNode.Icon = FolderIcon;
                rootNode.OpenIcon = FolderIconOpen;
                rootNode.NodeType = "init" + TreeAlias;
                rootNode.NodeID = "init";
                rootNode.Text = nodeTitle;
                rootNode.Action = "javascript:selectMediaItem();";
                rootNode.Source = GetTreeServiceUrl(NodeKey + "$-1");
            }
        }

        public override void Render(ref XmlTree tree)
        {
            if (NodeKey == "")
                return;

            var nodeKeyParts = NodeKey.Split('$');
            if (nodeKeyParts.Length < 2)
                return;

            var dtdId = Convert.ToInt32(nodeKeyParts[0]);
            var startMediaId = nodeKeyParts[1];

            if (dtdId == 0)
                return;

            var provider = UniversalMediaPickerProviderFactory.GetProvider(dtdId);
            if (provider == null)
                return;

            var mediaItems = UniversalMediaPickerCache.Get<IList<MediaItem>>(dtdId + "$GetMediaItems$" + startMediaId);
            if (mediaItems == null)
            {
                mediaItems = provider.GetMediaItems(startMediaId);

                var dt = DataTypeDefinition.GetDataTypeDefinition(dtdId).DataType as UniversalMediaPickerDataType;
                UniversalMediaPickerCache.Set(dtdId + "$GetMediaItems$" + startMediaId, mediaItems, DateTime.Now.AddSeconds(dt.Config.CacheDuration));
            }

            foreach (var mi in mediaItems)
            {
                var i = XmlTreeNode.Create(this);
                i.Text = mi.Title;
                i.Icon = mi.Icon;
                i.Action = mi.Selectable ? "javascript:selectMediaItem(" + mi.ToBasicMediaItem().SerializeToJson().Replace("'", "\'").Replace("\"", "\'") + @");" : "javascript:selectMediaItem();";
                i.Source = mi.HasChildren == true ? GetTreeServiceUrl(dtdId + "$" + mi.Id) : string.Empty;

                tree.Add(i);
            }
        }

        public override void RenderJS(ref System.Text.StringBuilder Javascript)
        {
            if (!string.IsNullOrEmpty(base.FunctionToCall))
            {
                Javascript.Append("function selectMediaItem(id) {\n");
                Javascript.Append(base.FunctionToCall + "(id);\n");
                Javascript.Append("}\n");
            }
            else if (!base.IsDialog)
            {
                Javascript.Append("\r\nfunction selectMediaItem(id) {\r\n\talert(id);\r\n}\r\n");
            }

        }
    }
}